<?php

/**
 * 压缩图片
 * @param string $imgsrc          图片文件路径
 * @param int    $maxWidth        压缩生成文件最大宽度
 * @param int    $number          压缩指数
 * @return mixed
 */
function compressImage(string $imgsrc, $maxWidth = 2000, $number = 80){
    if (!is_file($imgsrc)) {
        return false;
    }

    chmod($imgsrc, 0777);   #给图片赋权限

    $imgdst = $imgsrc;   #（新文件地址）覆盖源文件

    list($width, $height, $type) = getimagesize($imgsrc);

    $new_width = $width;//压缩后的图片宽
    $new_height = $height;//压缩后的图片高

    if($width >= $maxWidth){
        $per = $maxWidth / $width;//计算比例
        $new_width = $width * $per;
        $new_height = $height * $per;
    }

    switch ($type) {
        case 1:
            $giftype = check_gifcartoon($imgsrc);
            if ($giftype) {
                header('Content-Type:image/gif');
                $image_wp = imagecreatetruecolor($new_width, $new_height);
                $color = imagecolorallocate($image_wp,255,255,255);
                imagecolortransparent($image_wp, $color);
                imagefill($image_wp, 0, 0, $color);
                $image = imagecreatefromgif($imgsrc);
                imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                imagegif ($image_wp, $imgdst);
                imagedestroy($image_wp);
                imagedestroy($image);
            }
            break;
        case 2:
            header('Content-Type:image/jpeg');
            $image_wp = imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromjpeg($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            imagejpeg($image_wp, $imgdst, $number);
            imagedestroy($image_wp);
            imagedestroy($image);
            break;
        case 3:
            header('Content-Type:image/png');
            $image_wp = imagecreatetruecolor($new_width, $new_height);
            /* 针对透明背景处理Start */
            $color = imagecolorallocate($image_wp,255,255,255);
            imagecolortransparent($image_wp, $color);
            imagefill($image_wp, 0, 0, $color);
            /* 针对透明背景处理End */
            $image = imagecreatefrompng($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            //imagepng($image_wp, $imgdst);
            imagejpeg($image_wp, $imgdst, $number);
            imagedestroy($image_wp);
            imagedestroy($image);
            break;
    }
    #清除文件资源缓存
    clearstatcache();
    return $imgdst;
}
